<template>
  <container-item-wrapper :widget="widget">
    <vxe-toolbar>
      <template v-if="!isReadMode" #buttons>
        <el-button v-if="widget.options.add" type="primary" @click="insertEvent()">{{ i18nt('designer.setting.operateAdd') }}</el-button>
        <el-button v-if="widget.options.delete" @click="removeSelectRows()">{{ i18nt('designer.setting.operateDelete') }}</el-button>
        <el-button v-if="widget.options.import" @click="importData()">{{ i18nt('designer.setting.operateImport') }}</el-button>
        <el-button v-if="widget.options.export" @click="exportData()">{{ i18nt('designer.setting.operateExport') }}</el-button>
        <el-button v-if="widget.options.refresh" @click="refresh()">{{ i18nt('designer.setting.operateRefresh') }}</el-button>
        
         <el-button
          v-if="widget.options.name === 'IssueMatters' "
          @click="startupProcess()"
        >
          {{ '启动流程' }}
        </el-button>
        <el-button
          v-if="
            widget.options.name === 'affectedOrderInformation' ||
            widget.options.name === 'collectChangeObjects' ||
            widget.options.name === 'designatedInformationAffected' ||
            widget.options.name === 'EBOMInformationAffected' ||
            widget.options.name === 'MBOMInformationAffected' ||
            widget.options.name === 'CADInformationAffected' ||
            widget.options.name === 'partInformationAffected' ||
            widget.options.name === 'MZInformationAffected' ||
            widget.options.name === 'RZInformationAffected'
          "
          @click="collect()"
        >
          {{ '全选' }}
        </el-button>
        <el-button
          v-if="
            widget.options.name === 'affectedOrderInformation' ||
            widget.options.name === 'collectChangeObjects' ||
            widget.options.name === 'designatedInformationAffected' ||
            widget.options.name === 'EBOMInformationAffected' ||
            widget.options.name === 'MBOMInformationAffected' ||
            widget.options.name === 'CADInformationAffected' ||
            widget.options.name === 'partInformationAffected' ||
            widget.options.name === 'MZInformationAffected' ||
            widget.options.name === 'RZInformationAffected'
          "
          @click="exportPart()"
        >
          {{ '导出' }}
        </el-button>
        <el-button v-if="widget.options.name === 'affectedOrderInformation' || widget.options.name === 'collectChangeObjects'" @click="WriteForm()">
          {{ '写入表单' }}
        </el-button>
        <el-button
          v-if="
            widget.options.name === 'designatedInformationAffected' ||
            widget.options.name === 'EBOMInformationAffected' ||
            widget.options.name === 'MBOMInformationAffected' ||
            widget.options.name === 'partInformationAffected'
          "
          @click="WriteForm()"
        >
          {{ '保存' }}
        </el-button>
        <!-- <el-upload v-if="widget.options.name === 'partList'" action="" :http-request="importPart" :file-list="fileList" :show-file-list="false">
          <el-button size="small" type="primary">写入表单</el-button>
        </el-upload> -->
        <!-- <el-link v-if="widget.options.name === 'partList'" type="primary" @click="downloadTemplate()">下载模板</el-link> -->
        <!-- <el-button v-if="widget.options.name === 'inventoryList'" @click="inventory()">{{ '库存查询' }}</el-button> -->
        <!-- 变更对象列表 -->
        <!-- <el-button v-if="widget.options.name === 'changeItem'" @click="synchronous()">{{ '同步' }}</el-button> -->
        <!-- <el-button v-if="widget.options.name === 'changeItem'" :disabled="changeCollect" @click="collectRelatedObjects()">{{ '收集' }}</el-button> -->
        <!-- <el-button v-if="widget.options.name === 'changeItem'" :disabled="changeDelete" @click="removeSelectRowsChangeItem()">
          {{ i18nt('designer.setting.operateDelete') }}
        </el-button> -->
      </template>
    </vxe-toolbar>
    <vxe-grid
      ref="xGrid"
      v-bind="gridOptions"
      @checkbox-change="handleSelectionChange"
      :columns="columns"
      row-class-name="data-table-widget-row"
      class="data-table-item"
      :stripe="widget.options.stripe"
      :height="tableHeight"
      :footer-method="footerMethod"
      :style="{ width: this.widget.options.tableWidth || '100%' }"
      :show-footer="widget.options.showSummary"
    >
      <template #pager v-if="widget.options.showPagination">
        <vxe-pager
          :layouts="
            widget.options.smallPagination ? ['PrevPage', 'Number', 'NextPage'] : ['Total', 'PrevPage', 'Number', 'PageCount', 'NextPage', 'Sizes', 'FullJump']
          "
          :current-page="currentPage"
          :page-size="pageSize"
          :pageSizes="[5, 10, 20, 50, 100]"
          :total="gridOptions.data.length"
          :align="widget.options.paginationAlign"
          @page-change="handleCurrentPageChange"
        ></vxe-pager>
      </template>
    </vxe-grid>
    <select-object-dialog v-model="showDialog" :field="widget" @confirm="confirmFunc" />
    <div v-if="dialogVisible">
      <el-dialog title="相关对象列表" v-model="dialogVisible" :append-to-body="true">
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="subData">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </container-item-wrapper>
</template>
<script>
import formDesigner from '@common/form-designer';
import core from '@common/core'
const request = core.getExportResource('src/core/utils/http-tools.js').default;
// const FormItemWrapper = formDesigner.getExportResource('src/form-designer/extension/form-render/data-table-item.vue');
const FormItemWrapper = formDesigner.getExportResource(
  'src/form-designer/extension/form-render/data-table-item.vue'
)
if (!FormItemWrapper) {
  console.error('组件未加载成功')
}
export default {
  extends: FormItemWrapper.default,
  components: {},
  watch: {
    'widget.options.tableData': {
      handler(val) {
        this.widget.options.pagination.total = val.length;
        this.globalModel.formModel[this.widget.options.name] = val;
      },
      deep: true
    },
    // modify by nieyz 2024/10/22 业务规则设置表格只读时重置表单列形态
    'widget.options.readonly': {
      handler(val) {
        this.makeColumns();
      }
    }
  },
  data() {
    return {
      selections: [],
      dialogVisible: false,
      queryType: '',
      changeCollect: true,
      changeDelete: true
    };
  },
  mounted() {
    console.log(this.widget.options);
  },
  methods: {

    getObjectNumber() {
    // 获取完整的 URL
    const url = window.location.href;
    console.log(url);
    
    // 创建一个 URL 对象
    const urlObj = new URL(url);

    // 获取 objOrginalParam 参数（它是 JSON 字符串，但被编码了）
    const encodedParam = urlObj.searchParams.get('objOrginalParam');

    if (encodedParam) {
      try {
        // 先解码，再解析为 JSON
        const decodedParam = decodeURIComponent(encodedParam);
        const paramObj = JSON.parse(decodedParam);

        // 提取 objectNumber
        const objectNumber = paramObj.objectNumber;
        return objectNumber; // 返回如 "PR20250915004"
      } catch (error) {
        console.error('解析 objOrginalParam 失败:', error);
        return null;
      }
    } else {
      console.warn('URL 中没有找到 objOrginalParam 参数');
      return null;
    }
  },
  // 在 methods 中添加以下方法
// extractObjectNumberFromStorage() {
//   // 获取 sessionStorage 中的 vuex 数据
//   const vuexData = sessionStorage.getItem('vuex');
//   console.log('vuexData1111', vuexData);
//   if (vuexData) {
//     try {
//       // 解析 JSON 数据
//       const parsedData = JSON.parse(vuexData);
      
//       // 遍历 routeKey 对象提取 objectNumber
//       if (parsedData.routeKey && parsedData.routeKey.routeKey) {
//         const routeKeys = parsedData.routeKey.routeKey;
        
//         // 遍历所有子键获取 objectNumber、oid 和 otype
//         for (const key in routeKeys) {
//           const item = routeKeys[key];
//           if (item.objectNumber) {
//             const objectNumber = item.objectNumber;
//             const oid = item.oid || null;
//             const otype = item.otype || null;
            
//             console.log('提取到的 objectNumber:', objectNumber);
//             console.log('提取到的 oid:', oid);
//             console.log('提取到的 otype:', otype);
            
//             return {
//               objectNumber,
//               oid,
//               otype
//             };
//           }
//         }
//       }
//     } catch (error) {
//       console.error('解析 vuex 数据失败:', error);
//     }
//   } else {
//     console.warn('未找到 vuex 数据');
//   }
  
//   return null;
// },

   async startupProcess(){
  //  const result  =  this.extractObjectNumberFromStorage();
   const $table = this.$refs.xGrid;
    let selectData=[...$table.getCheckboxRecords()]
    console.log("vuexData",selectData);
    let data={
      list: selectData,
      objectNumber:   sessionStorage.getItem('PROID'),
      problemItemOid:  sessionStorage.getItem('projectOid'),
      problemItemOtype: sessionStorage.getItem('projectOType'),
    }
   const res = await request({
        url: '/rest/correction/v1/startProblemItemTask',
        method: 'post',
        data:data,
        headers: {
          authorization: sessionStorage.getItem('authorization')
        }
      });
      console.log(res);
      if (res.data.code === "200") {
        this.$message.success("启动成功");
      }
    },
    removeSelectRowsChangeItem() {
      const $table = this.$refs.xGrid;
      if ($table) {
        $table.removeCheckboxRow();
        this.widget.options.tableData = $table.getTableData()?.tableData || [];
      }
    },
    collectRelatedObjects() {
      this.dialogVisible = true;
      this.queryType = 'relatedObjects';
    },
    synchronous() {
      const $table = this.$refs.xGrid;
      this.formModel.partList.forEach((item) => {
        let dataFilter = this.widget.options.tableData.filter((data) => {
          return item.oid === data.oid;
        });
        if (dataFilter.length == 0) {
          $table.insert(item);
        }
      });
      $table.getTableData()?.tableData.forEach((item) => {
        let dataFilter = this.formModel.partList.filter((data) => {
          return item.oid === data.oid;
        });
        if (dataFilter.length === 0) {
          console.log('进行删除');

          $table.remove(item);
        }
      });
      //对比需要删除的数据
      this.widget.options.tableData = $table.getTableData()?.tableData || [];
    },
    handleSelectionChange(checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event) {
      console.log(checked.records);

      this.selections = checked.records;
      if (this.widget.options.name === 'changeItem') {
        let partLength = this.selections.filter((item) => {
          return item.otype === 'ty.inteplm.part.CTyPart';
        });
        let docLength = this.selections.filter((item) => {
          return item.otype === 'ty.inteplm.doc.CTyDoc';
        });

        if (partLength.length == this.selections.length) {
          this.changeCollect = false;
        } else {
          this.changeCollect = true;
        }

        if (docLength.length == this.selections.length) {
          this.changeDelete = false;
        } else {
          this.changeDelete = true;
        }
      }

      if (this.selections.length === 0) {
        this.changeCollect = true;
        this.changeDelete = true;
      }
    },
    subData() {
      const $table = this.$refs.xGrid;
      //   console.log(this.$refs.partItem.selections);

      //   this.$refs.partItem.selections.forEach((element) => {
      //     let filterData = $table.getTableData()?.tableData.filter((item) => {
      //       return item.oid === element.oid;
      //     });
      //     if (filterData.length === 0) {
      //       $table.insert(element);
      //     }
      //   });
      this.widget.options.tableData = $table.getTableData()?.tableData || [];
      this.dialogVisible = false;
    },
    collect() {
      //   this.dialogVisible = true;
      //   this.queryType = 'parentAndChildren';
    },
    WriteForm() {
      this.getFormRef().getParentFormRef().getWidgetRef('input86681').setValue('测试插入');
    },

    async importPart(file) {
      let formData = new FormData();
      const res = await request({
        method: 'get',
        url: '/rest/change/getOrderNo',
        headers: {
          authorization: sessionStorage.getItem('authorization')
        }
      });
      console.log(res);
      if (res.data.success) {
        const $table = this.$refs.xGrid;
        res.data.data.forEach((element) => {
          let filterData = this.widget.options.tableData.filter((item) => {
            return item.number === element.number && item.displayVariation1 === element.displayVariation1;
          });

          if (filterData.length === 0) {
            console.log(filterData);
            $table.insert(element);
          }
        });
        this.widget.options.tableData = $table.getTableData()?.tableData || [];
      }
    },
    async exportPart() {
      const $table = this.$refs.xGrid;

      const res = await request({
        method: 'post',
        url: '/rest/v1/zl/change/exportDataItem',
        data: $table.getTableData()?.tableData,
        responseType: 'blob',
        headers: {
          authorization: sessionStorage.getItem('authorization')
        }
      }).then((res) => {
        let typeCount = {
          type: 'application/octet-stream'
        };

        let _me = this;
        let blob = new Blob([res.data], typeCount);
        if (typeCount.type) {
          const fileReader = new FileReader();
          fileReader.readAsText(blob, 'utf-8');
          // fileReader.onload = function () {
          //     console.log("111");

          //     let msg = JSON.parse(fileReader.result).errors.message;
          //     return _me.$message.error(msg);
          // };
        }

        let fileName = res.headers['content-disposition'].split('filename=').pop();
        fileName = decodeURI(fileName);
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    async inventory() {
      let partNumberList = this.formModel.partList.map((item) => item.number);
      console.log(this.formModel);

      this.InventorQuery(partNumberList);
    },
    async InventorQuery(numberList) {
      const $table = this.$refs.xGrid;
      const res = await request({
        method: 'post',
        url: '/rest/v1/zl/queryInventory',
        data: numberList,
        headers: {
          authorization: sessionStorage.getItem('authorization')
        }
      });
      if (res.data.success) {
        console.log(res.data);

        if (res.data.data.code == 400) {
          this.$message.error(res.data.data.message);
          return;
        }

        res.data.data.data.forEach((item) => {
          let numberLength = $table.getTableData()?.tableData.filter((table) => {
            return table.number === item.productCode && item.orgName === table.orgName;
          });
          if (numberLength.length > 0) {
            $table.getTableData()?.tableData.forEach((table) => {
              if (item.productCode === table.number && item.orgName === table.orgName) {
                if (table.category == '在途') {
                  table.ERPquantity = item['in_transit_quantity'];
                } else if (table.category == '在制') {
                  table.ERPquantity = item['wip_quantity'];
                } else if (table.category == '库存') {
                  table.ERPquantity = item['inventory_quantity'];
                }
                $table.updateData(table);
              }
            });
          } else {
            console.log(item);
            if (item.in_transit_quantity !== 0) {
              $table.insert({
                number: item.productCode,
                orgName: item.orgName,
                category: '在途',
                ERPquantity: item.in_transit_quantity,
                sceneQuantity: '',
                sumQuantity: '',
                unit: item.in_transit_unit,
                disposition: ''
              });
            }
            if (item.wip_quantity !== 0) {
              $table.insert({
                number: item.productCode,
                orgName: item.orgName,
                category: '在制',
                ERPquantity: item.wip_quantity,
                sceneQuantity: '',
                sumQuantity: '',
                unit: item.wip_unit,
                disposition: ''
              });
            }
            if (item.inventory_quantity !== 0) {
              $table.insert({
                number: item.productCode,
                orgName: item.orgName,
                category: '库存',
                ERPquantity: item.inventory_quantity,
                sceneQuantity: '',
                sumQuantity: '',
                unit: item.inventory_unit,
                disposition: ''
              });
            }
          }
        });
        this.widget.options.tableData = $table.getTableData()?.tableData || [];
      }
    },
    async downloadTemplate() {
      console.log('执行');

      const res = await request({
        method: 'get',
        url: '/rest/v1/zl/change/downloadTemplate',
        responseType: 'blob',
        headers: {
          authorization: sessionStorage.getItem('authorization')
        }
      }).then((res) => {
        let typeCount = {
          type: 'application/octet-stream'
        };

        let _me = this;
        let blob = new Blob([res.data], typeCount);
        if (typeCount.type) {
          const fileReader = new FileReader();
          fileReader.readAsText(blob, 'utf-8');
          // fileReader.onload = function () {
          //     console.log("111");

          //     let msg = JSON.parse(fileReader.result).errors.message;
          //     return _me.$message.error(msg);
          // };
        }

        // let fileName = res.headers['content-disposition'].split('filename=').pop();
        let fileName = '物料列表导出模板.xlsx';
        fileName = decodeURI(fileName);
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    confirmFunc(data = []) {
      console.log(data);
      let numberList = data.map((item) => item.objectNumber);
      if (this.widget.options.name === 'inventoryList') {
        this.InventorQuery(numberList);
        return;
      }
      const $table = this.$refs.xGrid;
      if ($table && data?.length) {
        const insertData = data.map((row) => this.transRowToModel(row));
        $table.insert(insertData);
        this.widget.options.tableData = $table.getTableData()?.tableData || [];
      }
    },
    transRowToModel(row) {
      const obj = {
        oid: row.oid,
        branchid: row.branchid,
        otype: row.otype,
        type: row.classification,
        containerName: row.contextName,
        version: row.version + '.' + row.iterationid
      };
      this.widget.options.objectSelectData?.attrMap?.map(({ props, attr, widgetType }) => {
        obj[props] = this.transSpanToValue(attr, row);
      });
      console.log(obj);

      return obj;
    },
    getPropertyValue(row, propsKey) {
      // IBA属性从对象中取值
      if (propsKey.startsWith('iba_')) {
        const key = propsKey.split('iba_')[1];
        return row.ibaAttrMapForSearch ? row.ibaAttrMapForSearch[key] || '' : '';
      }
      // 有真值时取真值, 有额外值时取额外值
      return row[propsKey] ? row[propsKey] : row.extAttrMapForSearch ? row.extAttrMapForSearch[propsKey] || '' : '';
    },
    transSpanToValue(htmlString, row) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      const spans = doc.querySelectorAll('span');
      spans.forEach((span) => {
        // 获取span的父节点
        const parent = span.parentNode;
        const propsKey = span.getAttribute('value');
        // modify by nieyz 2025/4/14 将span的内容添加到父节点中，并移除span标签, iba属性取值要特殊处理
        parent.replaceChild(document.createTextNode(`${this.getPropertyValue(row, propsKey) || ''}`), span);
      });
      return doc.body.innerText;
    }
  }
};
</script>
